const express = require('express')
const router = express.Router()
const User = require('../models/User')
const TokenBlacklist = require('../models/TokenBlacklist')
const { generateToken } = require('../utils/auth')
const authMiddleware = require('../middlewares/auth')

// 用户注册
router.post('/register', async (req, res) => {
  try {
    const { username, password } = req.body
    const user = new User({ username, password })
    await user.save()
    res.status(201).json({ message: '注册成功' })
  } catch (err) {
    res.status(400).json({ message: err.message })
  }
})

// 用户登录
router.post('/login', async (req, res) => {
  try {
    const { username, password } = req.body
    console.log('Login attempt:', username) // 调试日志

    const user = await User.findOne({ username })
    if (!user || !(await user.comparePassword(password))) {
      return res.status(401).json({ message: '用户名或密码错误' })
    }

    const token = generateToken(user._id, user.role)
    console.log('Login successful, token generated for user:', username) // 调试日志
    res.json({
      token,
      userInfo: {
        userId: user.userId,
        username: user.username,
        role: user.role
      }
    })
  } catch (err) {
    console.error('Login error:', err) // 调试日志
    res.status(400).json({ message: err.message })
  }
})

// 获取当前用户信息
router.get('/queryUserInfo', authMiddleware(), async (req, res) => {
  try {
    const user = await User.findOne({ userId: req.query.userId }).select('-password')
    res.json({
      userId: user.userId,
      username: user.username,
      role: user.role
    })
  } catch (err) {
    res.status(400).json({ message: err.message })
  }
})

// 添加Token刷新接口
router.post('/refresh-token', authMiddleware(), async (req, res) => {
  try {
    const user = await User.findById(req.user.userId)
    if (!user) {
      return res.status(404).json({ message: '用户不存在' })
    }

    const newToken = generateToken(user._id, user.role)
    res.json({ token: newToken })
  } catch (err) {
    res.status(400).json({ message: err.message })
  }
})

// 退出登录
router.post('/logout', authMiddleware(), async (req, res) => {
  try {
    const token = req.header('Authorization')?.replace('Bearer ', '')
    if (!token) {
      return res.status(400).json({ message: '缺少Token' })
    }

    // 将Token加入黑名单
    await TokenBlacklist.create({ token })
    res.json({ message: '退出登录成功' })
  } catch (err) {
    res.status(500).json({ message: '退出登录失败' })
  }
})

// 删除用户 需要管理员权限
router.post('/deleteUser', authMiddleware(['admin']), async (req, res) => {
  try {
    const userId = req.body.userId // 从认证信息中获取被删除用户ID
    // 查找并删除用户
    const user = await User.findOne({ userId })

    if (!user) {
      return res.status(404).json({ message: '用户不存在' })
    }
    await User.deleteOne({ userId })
    res.json({ message: '用户删除成功' })
  } catch (err) {
    res.status(500).json({ message: '删除用户失败' })
  }
})

// 分页 获取所有用户
router.get('/getAllUsers', authMiddleware(), async (req, res) => {
  try {
    const pageNum = parseInt(req.query.pageNum) || 1
    const pageSize = parseInt(req.query.pageSize) || 10
    const skip = (pageNum - 1) * pageSize
    const users = await User.find().skip(skip).limit(pageSize)
    res.json({
      data: users.map(user => ({
        userId: user.userId,
        username: user.username,
        role: user.role
      })),
      total: users.length,
      pageNum,
      pageSize,
      message: '获取用户成功'
    })
  } catch (err) {
    res.status(500).json({ message: '获取用户失败' })
  }
})

module.exports = router
